﻿using Pay.Core;
using Pay.Data;
using Pay.DTO;
using Pay.IService;
using Pay.Service.Cache;
using Pay.TO;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Pay.Service.Service {
    class CourseService : ServiceBase, ICourseService, IDisposable {
        private IUnitOfWork _iUnitOfWork;
        public CourseService(IUnitOfWork iUnitOfWork) : base(iUnitOfWork) {
            _iUnitOfWork = iUnitOfWork;
        }
        public bool Delete(long id) {
            var model = context.Course.FindById(id);
            context.Course.Remove(model);
            int r = _iUnitOfWork.Commit();
            return r > 0;
        }

        public bool Enable(long id, bool isEnable) {
            var model = context.Course.FindById(id);
            model.IsEnable = isEnable;
            int r = _iUnitOfWork.Commit();
            return r > 0;
        }

        public course_dto Get(long id) {
            var model = context.Course.FindById(id).ToDtoObject<course_dto>();
            return model;
        }

        public PagedResult<course_dto> Gets(CourseQuery query) {
            var filter = PredicateBuilder.True<Course>();
            if (!string.IsNullOrEmpty(query.name))
                filter = filter.And(c => c.Name.Contains(query.name));
            if (query.start_time.HasValue) {
                long startTime = query.start_time.Value.ToUnix();
                filter = filter.And(c => c.UpdateTime >= startTime);
            }
            if (query.end_time.HasValue) {
                long endTime = query.end_time.Value.AddDays(1).ToUnix();
                filter = filter.And(c => c.UpdateTime <= endTime);
            }
            if (query.is_enable.HasValue) {
                filter = filter.And(c => c.IsEnable == query.is_enable.Value);
            }
            return context.Course.FromCachePaged<Course, course_dto>(query.page, query.size, filter, orderBy => orderBy.OrderByDescending(c => c.CreateTime));
        }

        public bool Save(course_dto dto) {
            if (dto.id == 0) {
                var prize = dto.ToDtoObject<Course>();
                prize.CreateTime = DateTime.Now.ToUnix();
                prize.UpdateTime = DateTime.Now.ToUnix();
                prize.IsEnable = true;
                context.Course.Add(prize);
            } else {
                var model = context.Course.FindById(dto.id);
                model.UpdateTime = DateTime.Now.ToUnix();
                dto.ToDtoObject(model);
            }
            int r = _iUnitOfWork.Commit();
            return r > 0;
        }


        #region API接口
        /// <summary>
        /// 获取我的课程列表
        /// </summary>
        /// <param name="query"></param>
        /// <param name="userId"></param>
        /// <returns></returns>
        public PagedResult<marketing_course_list_model> GetMyCoursePageList(MarketingCourseQuery query, long userId) {
            var filter = PredicateBuilder.True<Course>();
            filter = filter.And(c => c.IsEnable == true);
            if (query.id > 0)
                filter = filter.And(c => c.Id == query.id);
            if (!string.IsNullOrEmpty(query.name))
                filter = filter.And(c => c.Name.Contains(query.name));
            var q = from c in context.Course.Where(filter)
                    join h in context.UserSoupValueHis.Where(o => o.TaskType == ETaskType.WatchCourse && o.UserId == userId) on c.Id equals h.ItemId into t1
                    from th in t1.DefaultIfEmpty()
                    select new marketing_course_list_model() {
                        id=c.Id,
                        name = c.Name,
                        url = c.Url,
                        time_seconds = c.Time,
                        horse = th!=null ?th.SoupValue:c.Horse,
                        status_title = th!=null ?"已看完":"未看完",
                        update_time_value = c.UpdateTime
                    };
            var rows = q.OrderByDescending(c => c.update_time_value).Skip((query.page - 1) * query.size).Take(query.size).ToList();
            if (rows != null && rows.Count() > 0)
                rows.ForEach(o => { o.update_time = o.update_time_value.ToDateTime(); });
            var result = new PagedResult<marketing_course_list_model>(rows, q.Count(), query.page, query.size);
            return result;
        }

        /// <summary>
        /// 获取课程
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public marketing_course_model GetCourseById(long id) {
            var result = new marketing_course_model();
            var course = context.Course.FindById(id).ToDtoObject<course_dto>();
            if (course != null)
                course.ToCopyProperty(result);
            return result;
        }
        #endregion
    }
}